//
//  ZBKeyFrameAnimationView.m
//  送礼
//
//  Created by 华惠友 on 2017/9/19.
//  Copyright © 2017年 华惠友. All rights reserved.
//

#define SCREEN_WIDTH [UIScreen mainScreen].bounds.size.width
#define SCREEN_HEIGHT [UIScreen mainScreen].bounds.size.height
#import "ZBKeyFrameAnimationView.h"

@interface ZBKeyFrameAnimationView ()

@property (nonatomic, copy) AnimationFinishBlock finishedBlock;

@end

@implementation ZBKeyFrameAnimationView
static ZBKeyFrameAnimationView *_animationView = nil;

+ (instancetype)sharedInstance {
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        _animationView = [[self alloc] init];
    });
    return _animationView;
}

//- (instancetype)init{
//    if (self = [super init]) {
//        self.frame = CGRectMake(0, 0, SCREEN_WIDTH, SCREEN_HEIGHT);
//        [self addSubview:self.gifImageView];
//    }
//    return self;
//}

- (void)animationWithKeyFrame:(AnimationFinishBlock)finished {
    self.isAnimating = YES;     // 正在执行动画
    self.frame = CGRectMake(0, 0, SCREEN_WIDTH, SCREEN_HEIGHT);
    [self addSubview:self.gifImageView];
    
    self.finishedBlock = finished;
    
    NSMutableArray *tempArr = [NSMutableArray array];
    
    for (int i = 1; i < 26; i ++) {
        
        UIImage *image =  [UIImage imageNamed:[NSString stringWithFormat:@"meteor_after_%d",i]];;
        
        [tempArr addObject:image];
        
    }
    
    self.gifImageView.animationImages = tempArr;
    
    self.gifImageView.animationDuration = 2.5f;
    
    self.gifImageView.animationRepeatCount = 1;
    
    [self.gifImageView startAnimating];
    
    [self performSelector:@selector(deleteGif:) withObject:nil afterDelay:4];
}


- (void)deleteGif:(id)object{
    self.isAnimating = NO;     // 动画结束
    [_gifImageView stopAnimating];
    _gifImageView.animationImages = nil;
    [self removeFromSuperview];
    
    self.finishedBlock();
}

- (UIImageView *)gifImageView{
    if (_gifImageView == nil) {
        _gifImageView = [[UIImageView alloc]init];
        _gifImageView.frame = self.frame;
    }
    return _gifImageView;
}

@end
